<div class="layui-row">
  <div class="layui-col-lg3">
    <div class="layui-btn-group" id="device_handle_permi">
      <button class="layui-btn data_handle_btn">新申请</button>
<!--       <button class="layui-btn device_deliver">转移</button>
      <button type="button" class="layui-btn" id="file_input_btn"><i class="layui-icon"></i>文件导入</button> -->
    </div>
  </div>
  <div class="layui-col-lg3">
    <form class="layui-form layui-form-pane" action="">
        <div class="layui-form-item">
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <input type="text" l name="search_key"  placeholder="设备ID/名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <a class="layui-btn" lay-submit="" lay-filter="data-search-btn">搜索</a>
            </div>
        </div>
    </form>
  </div>
</div>

<table class="layui-table" id="base_info_manage_table" lay-filter="base_info_manage_table"></table>
<!-- 表格操作栏内容 -->
<!-- <script type="text/html" id="table_info_handle_bar">
  <a class="layui-btn layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-xs layui-btn-danger " lay-event="del">撤回</a>
  <a class="layui-btn layui-btn-xs data-count-edit" lay-event="re_submit">提交</a>
</script> -->

<script type="text/html" id="table_header">
  <p>用车申请管理表</p>
</script>

<!-- 添加数据表单开始 -->
<form  class="layui-form layui-form-pane " action="" id="handle_data_form" lay-filter="handle_data_form" style="padding: 10px;display: none;">
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">出发地</label>
      <div class="layui-input-block">
        <input type="text" name="start" onclick="get_address('start')" readonly="" lay-verify="required" lay-reqtext="必填项!" placeholder="出发地" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">目的地</label>
      <div class="layui-input-block">
        <input type="text" name="end" onclick="get_address('end')" lay-verify="required" lay-reqtext="必填项!" placeholder="目的地" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">用车事由</label>
      <div class="layui-input-block">
        <input type="text" name="purpose" lay-verify="required" lay-reqtext="必填项!" placeholder="用车事由" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">乘车人数</label>
      <div class="layui-input-block">
        <input type="text" name="passenger" lay-verify="required" lay-reqtext="必填项!" placeholder="用车事由" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">用车时间</label>
      <div class="layui-input-block">
        <input type="text" id="time_use" name="time_use" lay-verify="required" lay-reqtext="必填项!"  autocomplete="off" placeholder="用车时间" class="layui-input">
      </div>
    </div>
  </div>

<!--   <div class="layui-form-item" >
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green" >使用车辆</label>
      <div class="layui-input-block" >
        <input id="bind_device" name="car" type="text" list="bind_device_list"  name="tml_serch"  placeholder="使用车辆" autocomplete="off" class="layui-input">
          <datalist id="bind_device_list"></datalist>
      </div>
    </div>
  </div> -->

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">备注</label>
      <div class="layui-input-block">
        <input type="text" name="remark" placeholder="备注信息" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <button class="layui-btn layui-btn-fluid" id="add_submit_btn" lay-submit lay-filter="add_submit" >提交</button>
</form>

<!-- 添加数据表单结束 -->

<!-- 修改数据表单开始 -->
<form  class="layui-form layui-form-pane " action="" id="edit_data_form" lay-filter="edit_data_form" style="padding: 10px;display: none;">
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">出发地</label>
      <div class="layui-input-block">
        <input type="text" name="start" onclick="get_address('start')" readonly="" lay-verify="required" lay-reqtext="必填项!" placeholder="出发地" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">目的地</label>
      <div class="layui-input-block">
        <input type="text" name="end" onclick="get_address('end')" lay-verify="required" lay-reqtext="必填项!" placeholder="目的地" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">用车事由</label>
      <div class="layui-input-block">
        <input type="text" name="purpose" lay-verify="required" lay-reqtext="必填项!" placeholder="用车事由" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">乘车人数</label>
      <div class="layui-input-block">
        <input type="text" name="passenger" lay-verify="required" lay-reqtext="必填项!" placeholder="用车事由" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">用车时间</label>
      <div class="layui-input-block">
        <input type="text" id="change_time_use" name="time_use" lay-verify="required" lay-reqtext="必填项!"  autocomplete="off" placeholder="用车时间" class="layui-input">
      </div>
    </div>
  </div>

<!--   <div class="layui-form-item" >
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green" >使用车辆</label>
      <div class="layui-input-block" >
        <input id="change_car" name="car" type="text" list="change_car_list"  name="tml_serch"  placeholder="选择设备" autocomplete="off" class="layui-input">
          <datalist id="change_car_list"></datalist>
      </div>
    </div>
  </div> -->

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">备注</label>
      <div class="layui-input-block">
        <input type="text" name="remark" placeholder="备注信息" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item" style="display: none;">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">存储id</label>
      <div class="layui-input-block">
        <input type="text" name="id" placeholder="备注信息" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <button class="layui-btn layui-btn-fluid" id="edit_submit_btn" lay-submit lay-filter="edit_submit" >提交</button>
</form>

<!-- 修改数据表单结束 -->

<!-- 设备转移表单 开始-->
<div class="layui-container" id="device_deliver_div" style="display: none;padding: 20px">
    <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green" style="text-align: center;">转移到</label>
      <div class="layui-input-block">
       <input type="text" list="deliver_target" name="" class="layui-input" id="dev_to_user">
        <datalist id="deliver_target">
        </datalist>
      </div>
    </div>
  </div>
  <table id="user_tree"  class="layui-table"></table>
</div>
<!-- 设备转移表单 结束-->

<!-- 设备导入处理开始 -->
<div class="layui-form-item" style="display: none;">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">id</label>
      <div class="layui-input-block">
        <input type="text" name="device_input"  autocomplete="off" class="layui-input" id="device_input">
      </div>
    </div>
</div>
<!-- 设备导入处理结束 -->

<!-- 弹窗展示地图 -->
<div style="display: none;" id="map_panle">
  <div id="map_box" style="height: 500px;width: 920px"></div>
  <div class="layui-inline" style="position: absolute;top: 5px;left: 0px;">
      <div class="layui-input-inline">
          <input type="text"  id="search_address"  placeholder="搜索地址" autocomplete="off" class="layui-input" style="height: 30px;">
      </div>
      <!-- <div class="layui-form-mid layui-word-aux"></div> -->
      <a type="button" class="layui-btn layui-btn-sm" onclick="search_map($('#search_address').val())">搜索</a>
  </div>
</div>

<!-- 引入把上传的表格转变为json的插件 -->
<script src="/static/js/xlsx.js"></script>
<script type="text/javascript" src="/static/js/bd_map.js"></script>
<!-- js代码开始 -->

<script type="text/javascript">
if(user_permi==='normal'){
  $('#device_handle_permi').hide()
}

var ajax_url='car_apply'


map.addEventListener('click', function(e){
  map.clearOverlays()
  
  geoc.getLocation(e.point, function(rs){
    var addComp = rs.address
    var location
    if(rs.surroundingPois.length!=0){
      // console.log(rs)
       location=addComp+','+rs.surroundingPois[0]['title'] 
    }else{
       location=addComp
    }
    console.log(location)
    point_kind.value=location+'&'+e.point.lng+'&'+e.point.lat
    var m=new BMap.Marker(e.point)
    var mylabel=new BMap.Label(location,{offset:new BMap.Size(-3,-25)});
    m.setLabel(mylabel);
    map.addOverlay(m)
  });
  // layer.msg(p)
});


// 设备数据表格渲染函数

var table_show=function(table_data){
  // console.log(table_data)
  apply_data=table_data
  // car_data=table_data['car_data']
  table.render({
    elem: '#base_info_manage_table',
    toolbar:'#table_header',
    data: apply_data,
    id:'base_info_manage_table',
    cols: [[
        {type: "checkbox", fixed: "left"},
        // {field: 'id', title: 'ID',width:20,sort:true},
        {field: 'start', title: '出发地',sort:true},
        {field: 'end', title: '目的地',sort:true},
        {field: 'purpose', title: '用车事由',sort:true},
        {field: 'passenger', title: '乘车人数',sort:true},
        {field: 'time_use', title: '用车时间',sort:true},
        {field: 'car', title: '使用车辆',sort:true},
        {field: 'status', title: '状态',sort:true,templet:function(d){
          var value=d.status
          var param_set=eval('('+d.param_set+')')
          if(d.status=='审批通过'){
            if(param_set.key_status=='un_get'){
              value=value+',取钥匙码：'+param_set.get_key_code
            }
          }else if(d.status=='审批未通过'){
            value=value+'：'+param_set.reject
          }
          return value
        }},
        {field: 'apply_time', title: '申请时间',sort:true},
        {field: 'remark', title: '备注',sort:true},
        {title: '操作', minWidth: 110, templet: function(d){
          var value=''
          var a='<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>'
          var b='<a class="layui-btn layui-btn-xs layui-btn-normal " lay-event="del">撤回</a>'
          var c='<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="re_submit">提交</a>'
          if(d.status=='撤回'){
            value=a+c
          }else if(d.status=='已提交，待审批'){
            value=b
          }
          return value
        }, fixed: "right", align: "center"}
    ]],
    limits: [10, 15, 20, 25, 50, 100],
    limit: 10,
    page: true
  });
}

// 首次用户数据加载
var apply_data;
var car_data;
// 首次用户数据加载,index页面加载设备和型号信息
get_info_ajax(ajax_url,'get_init_data',table_show)

// 监听添加操作
$(".data_handle_btn").on("click", function () {
    document.getElementById("handle_data_form").reset();
    form.render();
    // 图片上传功能
    // fill_raido_func(car_data,'bind_device_list','none','name')
    point_kind.form_name='handle_data_form'
    layer.open({
        type: 1
        ,title:'新增申请信息'
        // ,area:['920px','550px']
        ,offset:'60px'  
        ,id: 'add_data' //防止重复弹出
        ,content:$('#handle_data_form')
        ,shade: 0 //不显示遮罩
        // ,btn: ['提交','关闭']
        // ,btn1: function(){
        // }
        // ,btn2: function(index){
        //   layer.close(index.selector);
        // }
      });
});

// 监听添加操作,并提交
form.on('submit(add_submit)',function(obj){
  obj.field.status='已提交，待审批'
  var base_info=package_data(obj.field)
  // console.log(base_info)
  post_info_ajax(base_info,ajax_url,'add',table_show)
  return false
})

// 在地图上采集起点和终点
var point_kind={'kind':'start','value':'','form_name':'handle_data_form'};
var get_address=function(kind){
  console.log(kind)
  point_kind.kind=kind
  layer.open({
    type: 1
    ,area:['920px','610px']
    ,offset:'60px'  //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
    ,id: 'map_show' //防止重复弹出
    ,content:$('#map_panle')
    ,shade: 0 //不显示遮罩
    ,btn: ['提交','关闭']
    ,btn1: function(index, layero){
      // console.log(point_kind.value)
      var location_value={}
      location_value[point_kind['kind']]=point_kind.value
      form.val(point_kind.form_name,location_value)
      layer.close(index);
    }
    ,btn2: function(){
      var location_value={}
      location_value[point_kind['kind']]=''
      form.val(point_kind.form_name,location_value)
    }
    });
}

// 监听操作按钮，编辑/启停\
var edit_data_chose
table.on('tool(base_info_manage_table)', function (obj) {

  var result = obj.data;
  point_kind.form_name='edit_data_form'
  document.getElementById("edit_data_form").reset();
  var time_use=eval(result.time_use).join(' - ')
  result.time_use=time_use
  form.val('edit_data_form',result)
  // fill_raido_func(car_data,'change_car_list','none','name')
  form.render()

  if(obj.event=='edit'){
    if(result.status!=='撤回'){
      layer.msg('请先操作撤回申请')
      return
    }
    layer.open({
    type: 1
    ,title:'修改申请信息'
    ,offset:'60px'  //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
    ,id: 'edit_data' //防止重复弹出
    ,content:$('#edit_data_form')
    ,shade: 0 //不显示遮罩
    });
  }else if(obj.event=='del'){
    if(result.status!=='已提交，待审批'){
      layer.msg('已提交，待审批的申请才能操作撤回')
      return
    }
    layer.confirm("确定撤回申请？",
              {btn: ['是', '否']}, 
              function (index) {
                var base_info=package_data(result)
                base_info['status']='撤回'
                console.log(base_info)
                post_info_ajax(base_info,ajax_url,'edit',table_show)
              }
              ,function(){
                console.log('no')
                layer.closeAll()
              });
  }
  else if(obj.event=='re_submit'){
    if(result.status!=='撤回'){
      layer.msg('请先操作撤回申请')
      return
    }
    layer.confirm("确定提交？",
              {btn: ['是', '否']}, 
              function (index) {
                var base_info=package_data(result)
                base_info['status']='已提交，待审批'
                post_info_ajax(base_info,ajax_url,'edit',table_show)
              }
              ,function(){
                console.log('no')
                layer.closeAll()
              });
  }
});


// 监听修改操作,并提交
form.on('submit(edit_submit)',function(obj){
  var base_info=package_data(obj.field)
  base_info['status']='已提交，待审批'
  console.log(base_info)
  post_info_ajax(base_info,ajax_url,'edit',table_show)
  return false
})


//封装数据
var package_data=function(result){
  var time_use=result.time_use.split(' - ')
  time_use=JSON.stringify(time_use)
  result.time_use=time_use

  return result
}


// 获取设备数据表格选中的数据，弹出用户结构弹窗，选择转移的目标用户，提交后台处理
$('.device_deliver').click(function(){
  var data_check=table.checkStatus('base_info_manage_table').data
  if(data_check.length===0){
    layer.msg('请选择需要转移的设备')
    return false
  }
  // 渲染用户树形结构
  tree.render({
    elem: '#user_tree'
    ,data: user_tree
    ,showCheckbox: false  //是否显示复选框
    ,id: 'id'
    ,onlyIconControl:true
    ,isJump: false //是否允许点击节点时弹出新窗口跳转
    ,text: {
            defaultNodeName: '未命名' //节点默认名称
            ,none: '无数据' //数据为空时的提示文本
          }   
    ,click: function(obj){
      var data = obj.data;  //获取当前点击的节点数据
      console.log(data)
      if(data['name']=='all'){
        layer.msg('该选择无效！')
        return false
      }
      $('#dev_to_user').val(data['name'])
    }

  });
  // 加载所有下级用户名称
  for(var i=0;i<user_data.length;i++){
    var user_name_option='<option>'+user_data[i]['visible_name']+'</option>'
    $('#deliver_target').append(user_name_option)
  }
// 弹窗，展示用户树形结构，选择用户，提交后台
  layer.open({
        type: 1
        ,title:'设备转移'
        ,area:['400px','500px']
        ,offset:'60px'  
        ,id: 'device_deliver' //防止重复弹出
        ,content:$('#device_deliver_div')
        ,btn: ['提交','关闭']
        ,shade: 0 //不显示遮罩
        ,btn1: function(){
            var result={};
            var target_user=$('#dev_to_user').val()
            var dev_to_user=[]
            for(var i=0;i<data_check.length;i++){
              dev_to_user.push(data_check[i]['name'])
            }
            result['name']=dev_to_user
            result['target_user']=target_user
            layer.confirm('确定转移到'+target_user, function (index) {
              post_info_ajax(result,ajax_url,'change_owner',table_show)
            })
        }
        ,btn2: function(){
          layer.closeAll();
        }
      });

})


// 监听 导入文件 按钮，做展示和修改操作处理
$('#file_input_btn').click(function(){
  var input = document.createElement('input');
  input.type = 'file';

  input.addEventListener('change', function() {
    var file = this.files[0];
    var reader = new FileReader();

    reader.onload = function (e) {
      var data = e.currentTarget.result;
      var wb = XLSX.read(data,{type:'binary'})
      var j_data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
      console.log(j_data)
      if(j_data[0]['__EMPTY']!=null){
        layer.msg('表格出错')
        return false
      }

      var batch_add_data=[];
      for(var i=0;i<j_data.length;i++){
         if(j_data[i]['name']!==0 && j_data[i]['name']!=='0'  && j_data[i]['name']!=='' && j_data[i]['name']!=null){
          batch_add_data.push(j_data[i])
         }  
      }

      layer.confirm('确定导入'+batch_add_data.length.toString()+'条车辆信息', function (index) {
              post_info_ajax(batch_add_data,ajax_url,'add_from_file',table_show)

            })

    }
    reader.readAsBinaryString(file)
  })

    input.click();
})



// 监听设备搜索操作
form.on('submit(data-search-btn)', function (data) {

  var search_key = data.field['search_key'];
  if(search_key!==''){
    // 调用index页面搜索函数
    var search_result=search_func(apply_data,search_key,'name','device_id')
    // 表格重载
    table_show(search_result)
  }else{
    table_show(apply_data)
  }
  return false;
});

//时间范围
laydate.render({
  elem: '#time_use'
  ,type: 'datetime'
  ,range: true
});

laydate.render({
  elem: '#change_time_use'
  ,type: 'datetime'
  ,range: true
});

</script>